package svc

import (
	"github.com/gorilla/websocket"
	"sync"
)

type ConnectionPool struct {
	connections []*websocket.Conn
	maxSize     int
	mutex       sync.Mutex
	url         string
}

func NewConnectionPool(maxSize int, url string) *ConnectionPool {
	var connections = make([]*websocket.Conn, 0, maxSize)
	for i := 0; i < maxSize; i++ {
		conn, _, err := websocket.DefaultDialer.Dial(url, nil)
		if err == nil {
			connections = append(connections, conn)
		}
	}

	return &ConnectionPool{
		connections: connections,
		maxSize:     maxSize,
		url:         url,
	}
}

func (pool *ConnectionPool) Get() *websocket.Conn {
	pool.mutex.Lock()
	defer pool.mutex.Unlock()
	if len(pool.connections) == 0 {
		//return nil
		// 这里实例化一个websocket连接
		conn, _, err := websocket.DefaultDialer.Dial(pool.url, nil)
		if err == nil {
			// 处理连接错误
			return conn
		}
	}
	conn := pool.connections[0]
	pool.connections = pool.connections[1:]
	return conn
}

func (pool *ConnectionPool) Put(conn *websocket.Conn) {
	pool.mutex.Lock()
	defer pool.mutex.Unlock()
	if len(pool.connections) < pool.maxSize {
		pool.connections = append(pool.connections, conn)
	} else {
		conn.Close()
	}
}

func (pool *ConnectionPool) Count() int {
	pool.mutex.Lock()
	defer pool.mutex.Unlock()
	return len(pool.connections)
}

//func (pool *ConnectionPool) GetWithTimeout(timeout time.Duration) (*websocket.Conn, error) {
//	select {
//	case <-time.After(timeout):
//		// 返回一个连接
//		conn, _, err := websocket.DefaultDialer.Dial(pool.url, nil)
//		if err == nil {
//			// 处理连接错误
//			return conn, nil
//		}
//		return nil, err
//	default:
//		conn := pool.Get()
//		if conn != nil {
//			return conn, nil
//		}
//		// 如果连接池中没有可用连接，返回nil，不会等待超时
//		return nil, nil
//	}
//}
